<template>
<v-file-input
  v-model="file"
  accept=".csv"
  label="选择文件"
  prepend-icon="mdi-file"
  outlined
  dense
  @click:clear="clear"
></v-file-input>
<v-radio-group v-model="radio" inline >
  <v-radio label="注册学生" :value="Role.Student"></v-radio>
  <v-radio label="注册教师" :value="Role.Teacher"></v-radio>
</v-radio-group>
<v-container class="d-flex flex-column">
  <v-dialog max-width="1080">
  <template #activator="{ props: activatorProps }">
    <v-btn @click="preView" v-bind="activatorProps" color="primary" :disabled="disable" class="my-5">预览</v-btn>
  </template>
  <template #default="{isActive}">
    <v-card v-show="isActive">
      <v-card-title>预览</v-card-title>

      <v-card-text>
        <v-data-table
          :items="items"
          item-key="index"
        >
        </v-data-table>
      </v-card-text>
    </v-card>
  </template>
</v-dialog>

<v-dialog v-model="dialog">
  <v-card>
    <v-card-title>提示</v-card-title>
    <v-card-text>{{ dialogMsg }}</v-card-text>
    <v-card-actions>
      <v-btn @click="dialog = false">确定</v-btn>
    </v-card-actions>
  </v-card>
</v-dialog>

<v-btn @click="upload" color="primary" :disabled="disable" class="my-5">上传并注册</v-btn>
</v-container>



</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import Papa from 'papaparse'
import { API } from '@/services';
import { Role } from '@/services/users/types';
const radio = ref(Role.Student)
const file = ref<File>()
const items = ref<object[]>([])

// 对话框是否打开
const dialog = ref(false)
const dialogMsg = ref('')
function openDialog(msg: string) {
  dialogMsg.value = msg
  dialog.value = true
}

// 清空文件
function clear() {
  file.value = undefined
  items.value = []
}

// 控制按钮是否可用
const disable = computed(() => file.value === undefined)

// 处理上传文件
function upload() {
  API.users.importUserInfo({
    registerRole: radio.value,
    csv_file: file.value!
  }).then(() => {
    clear()
    openDialog('注册成功')
  })
  .catch((err) => {
    console.log(err)
    openDialog(err.response.data)
  })
}

// 处理预览
function preView() {
  if (file.value === null) return
  Papa.parse(file.value!, {
    header: true,
    complete: (results) => {
      items.value = results.data as object[]
    }
  })
}


</script>
